//
//  CommentVC.m
//  MeiXiu
//
//  Created by Yuan on 12-10-31.
//
//

#import "CommentVC.h"
#import "CommentCell.h"
#import "OriginContentCell.h"
#import "CommentToolBar.h"
#import "HYProgressHUD.h"
#import "UIImageView+WebCache.h"
#import "UIButton+WebCache.h"
#import "ZoomImageView.h"

#define IMG_SIZE  CGSizeMake(200, 238)


@interface CommentVC ()<CommentToolBarDelegate,UITableViewDelegate,UITableViewDataSource>
{        
    NSInteger page;
        
    BOOL nextpage;
    
    NSString *commentID;
    
    BOOL isRequesting;
    
    UIView *maskView;
    
    NSString *commentContent;
}
@property(nonatomic,retain)IBOutlet UITableView *commentTableView;
@property(nonatomic,retain)NSMutableArray *dataArr;
@property(nonatomic,retain)UITextView *calculateTextView;
@property(nonatomic,retain)CommentToolBar *commentToolBar;
@property(nonatomic,retain)UIView *loadFooterView;
@property(nonatomic,retain)NSDictionary *info;
@end

@implementation CommentVC
@synthesize dataArr = _dataArr;
@synthesize calculateTextView = _calculateTextView;
@synthesize commentTableView = _commentTableView;
@synthesize commentToolBar = _commentToolBar;
@synthesize loadFooterView = _loadFooterView;
@synthesize shareID;
@synthesize info = _info;
@synthesize fromViewController;

-(void)dealloc
{
    [self removeNotifications];
    
    commentContent = nil;

    [_info release];_info = nil;
    [_loadFooterView release];_loadFooterView = nil;
    [_commentToolBar release];_commentToolBar = nil;
    [_commentTableView release];_commentTableView = nil;
    [_calculateTextView release];_calculateTextView = nil;
    [_dataArr release];_dataArr = nil;
    [super dealloc];
}

-(void)viewDidUnload
{
    self.loadFooterView = nil;
    self.commentToolBar = nil;
    self.commentTableView = nil;
    self.calculateTextView = nil;
    [super viewDidUnload];
}

- (id)initWithInfo:(NSDictionary *)dict
{
    self = [super initWithNibName:nil bundle:nil];
    if (self)
    {
        _info = [[NSDictionary  alloc]initWithDictionary:dict];
        
        commentID = @"";
        
        page = 0;
        
        HYLog(@"_info--->%@",_info);
        
        _dataArr = [[NSMutableArray alloc]init];
        
        _calculateTextView = [[UITextView alloc] initWithFrame:CGRectMake(0,0,260.0f,80.0f)];
        [_calculateTextView setHidden:YES];
        [_calculateTextView setFont:[UIFont systemFontOfSize:16.0]];
        [self.view addSubview:_calculateTextView];
        
    }
    return self;
}


-(void)loadView
{
    [super loadView];
    
    _commentTableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
    _commentTableView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
    _commentTableView.delegate = self;
    _commentTableView.dataSource = self;
    _commentTableView.backgroundColor = [UIColor clearColor];
    _commentTableView.backgroundView = nil;
    [self.view addSubview:_commentTableView];
}


- (void)viewDidLoad
{
    [super viewDidLoad];

    [self setTitle:HYLocalizedString(@"评论") showBackButton:YES];

    self.view.backgroundColor = [UIColor colorWithRed:1.000 green:0.884 blue:0.950 alpha:1.000];
    self.commentTableView.backgroundColor = [UIColor clearColor];
    self.commentTableView.backgroundView = nil;
    self.commentTableView.separatorColor = [UIColor colorWithRed:0.932 green:0.804 blue:0.861 alpha:0.000];
    self.commentTableView.rowHeight = 480.0f;
    UIView *footer = [[UIView alloc]initWithFrame:CGRectZero];
    self.commentTableView.tableFooterView = footer;
    [footer release];
    
    maskView = [[UIView alloc]initWithFrame:self.view.frame];
    [self.view addSubview:maskView];
    [maskView setHidden:YES];
    
    UITapGestureRecognizer *tapGest = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(clickAction:)];
    [maskView addGestureRecognizer:tapGest];
    [tapGest release];
    
    CGRect frame = self.view.frame;
    CGRect rect = CGRectMake(0, frame.size.height - 44, frame.size.width,frame.size.height);
    _commentToolBar = [[CommentToolBar alloc]initWithFrame:rect delegate:self];
    [self.view addSubview:_commentToolBar];
    
    _loadFooterView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 44)];
    UILabel *tipLbl = [[UILabel alloc]initWithFrame:CGRectMake(80, 9, 145, 21)];
    [tipLbl setText:HYLocalizedString(@"加载更多...")];
    [tipLbl setBackgroundColor:[UIColor clearColor]];
    [tipLbl setTextAlignment:UITextAlignmentCenter];
    [_loadFooterView addSubview:tipLbl];
    [tipLbl release];
    UIActivityIndicatorView *act = [[UIActivityIndicatorView alloc]initWithFrame:CGRectMake(52, 11, 20, 20)];
    [act startAnimating];
    [act setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleGray];
    [_loadFooterView addSubview:act];
    [act release];
    
    [self registerForKeyboardNotifications];
}



-(void)setShareID:(NSString *)shareID_
{
    shareID = shareID_;    
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self refresh];
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [_commentToolBar setText:commentContent];
}


-(void)refresh
{
    NSDictionary *p = [NSDictionary dictionaryWithObjectsAndKeys:
                       [NSString stringWithFormat:@"%d",page],@"page",
                       shareID,@"share_id",
                       nil];
    [WebService  getRequestAction:APICommentList
                            param:p
                          success:^(NSDictionary *retid,NSError *error)
     {
         if (error == nil)
         {
             nextpage =[[retid objectForKey:@"nextpage"] boolValue];
             NSArray *result = [retid objectForKey:@"result"];
             if (result && [result isKindOfClass:[NSArray class]] &&[result count]>0)
             {
                 [_dataArr removeAllObjects];
                 
                 for (int i = 0 ; i < [result count]; i++)
                 {
                     NSMutableDictionary *item = [[NSMutableDictionary alloc]initWithDictionary:[result objectAtIndex:i]];
                     CGFloat replyHeight = 0.0f;
                     CGFloat rowHeight = 0.0f;
                     CGFloat iconHeight = 42.0f;
                     NSString *rowContent = [MSTool trimmingWhiteSpaceCharacter:[item objectForKey:@"content"]];
                     CGRect txtViewFrame = _calculateTextView.frame;
                     txtViewFrame.size.width  = 260.0f;
                     _calculateTextView.frame = txtViewFrame;
                     [_calculateTextView setText:rowContent];
                     rowHeight = iconHeight+ _calculateTextView.contentSize.height;
                     NSArray *replylist =  [item objectForKey:@"re_list"];
                     if (replylist && [replylist isKindOfClass:[NSArray class]] &&[replylist count]>0)
                     {
                         txtViewFrame.size.width  = 200.0f;
                         _calculateTextView.frame = txtViewFrame;
                         CGFloat tmpReplyHeight = 0.0f;
                         for (int j = 0 ; j < [replylist count]; j++)
                         {
                             NSDictionary *reply = [replylist objectAtIndex:j];
                             NSString *replyContent = [MSTool trimmingWhiteSpaceCharacter:[reply objectForKey:@"content"]];
                             [_calculateTextView setText:replyContent];
                             tmpReplyHeight = _calculateTextView.contentSize.height + 48.0f;
                             replyHeight+=tmpReplyHeight;
                         }
                         replyHeight-= 15*([replylist count]-1);
                         replyHeight+=10.0f;
                     }
                     rowHeight += replyHeight;
                     [item setObject:[NSNumber numberWithFloat:replyHeight] forKey:@"replyheight"];
                     [item setObject:[NSNumber numberWithFloat:rowHeight] forKey:@"rowheight"];
                     [_dataArr addObject:item];
                     [item release];
                 }
                 HYLog(@"%d",[_dataArr count]);
                 [_commentTableView performSelector:@selector(reloadData) withObject:nil afterDelay:0.5];
             }
         }
         else
         {
             [MSTool showAlertTitle:HYLocalizedString(@"获取数据失败") message:[retid objectForKey:@"message"]];
         }             
         [MSTool showError:error];
     } failure:^(id info ,NSError *error){
         [MSTool showError:error];
     } progress:self.navigationController.view];
}


-(void)sendComment:(NSString *)comment
{
	if (commentContent) {
		[commentContent release];
	}
	commentContent=[comment retain];
    
    NSDictionary *p = [NSDictionary dictionaryWithObjectsAndKeys:
                                [[MSSetting sharedSetting]getAccountID],@"uid",shareID,@"share_id",comment,@"content",commentID,@"parent_id",nil];

    [WebService  getRequestAction:APISendComment
                            param:p
                          success:^(NSDictionary *info,NSError *error)
     {
         if (error == nil)
         {             
             HYLog(@"%@",info);
             [MSTool refreshHUDText:HYLocalizedString(@"发送成功!")];
             
             [_dataArr removeAllObjects];
             commentID = @"";
             page = 0;
             [self refresh];
         }
         [MSTool showError:error];
     } failure:^(id info ,NSError *error){
         [MSTool showError:error];
     } progress:self.navigationController.view];    
}


#pragma CommentToolBarDelegate methords
-(void)toolBarButtonDone:(UIButton *)_btn toolBarView:(CommentToolBar *)_toolBar text:(NSString *)_text
{
    [_toolBar resignFirstResponder];
    if ([_text length]>0)
    {
        [self sendComment:_text];
    }
    else
    {
        commentID = @"";
    }
}

-(void)toolBarShoulReturn:(CommentToolBar *)_toolBar
{
    commentID = @"";
    [_toolBar resignFirstResponder];
}

-(void)toolBarDidBegainEditing:(CommentToolBar *)_toolBar
{
    //
}

-(void)toolBarDidEndEditing:(CommentToolBar *)_toolBar
{
 //
}

- (void) registerForKeyboardNotifications
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardWillShowNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasHidden:) name:UIKeyboardWillHideNotification object:nil];
}

-(void)removeNotifications
{
	[[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardWillShowNotification object:nil];
	[[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardDidShowNotification object:nil];
    [[NSNotificationCenter defaultCenter]removeObserver:_commentToolBar name:@"HiddenKeybord" object:nil];
}

- (void) keyboardWasShown:(NSNotification *) notif
{
    [maskView setHidden:NO];

    NSDictionary *info = [notif userInfo];
    NSValue *value = [info objectForKey:UIKeyboardFrameEndUserInfoKey
                      ];
    CGSize keyboardSize = [value CGRectValue].size;    
	[UIView beginAnimations:nil context:nil];
	[UIView setAnimationDuration:0.30];
    _commentToolBar.frame=CGRectMake(0, self.view.bounds.size.height-keyboardSize.height-44.0f,
                             _commentToolBar.frame.size.width,
                             _commentToolBar.frame.size.height);
	[UIView commitAnimations];
}

- (void) keyboardWasHidden:(NSNotification *) notif
{
    [maskView setHidden:YES];

	[UIView beginAnimations:nil context:nil];
	[UIView setAnimationDuration:0.30];
	_commentToolBar.frame=CGRectMake(0, self.view.bounds.size.height-44.0f,
                             _commentToolBar.frame.size.width,
                             _commentToolBar.frame.size.height);
	[UIView commitAnimations];
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0)return 1;
    return [_dataArr count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *CellIdentifier = [NSString stringWithFormat:@"cell%d",indexPath.section];
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (indexPath.section == 0)
    {
        if (cell == nil)
        {
            cell = [[[OriginContentCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
        }
        OriginContentCell *oCell = (OriginContentCell *)cell;
        [oCell.iconButton setImageWithURL:[NSURL URLWithString:[_info objectForKey:@"avatar"]] forState:UIControlStateNormal];
        NSString *username =[_info objectForKey:@"user_name"];
        if ([username isEqual:[NSNull null]])username = @"";
        oCell.aliasLable.text = username;
        oCell.timeLbl.text =  [_info objectForKey:@"create_time"];
        [oCell.contentLbl setText:[_info objectForKey:@"content"]];
        NSString *pictureurl = [_info objectForKey:@"src"];
        BOOL isUrlExist = pictureurl!=nil&&[pictureurl length]>0?YES:NO;
//        CGSize imgSize = CGSizeMake([[_info objectForKey:@"width"] floatValue], [[_info objectForKey:@"height"] floatValue]);
//        CGSize  size_ =  [AppService getFitSizeFromCGSize:imgSize withMaxWidth:kCONTENT_IMG_WIDTH_MAX withMaxHeight:kCONTENT_IMG_HEIGHT_MAX];

        [oCell.pictureThumbButton setFrame:CGRectMake(90.0f,100.0f, IMG_SIZE.width, IMG_SIZE.height)];

        UITapGestureRecognizer *g = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(actionPictureTapGestureRecognizer:)];
        [oCell.pictureThumbButton addGestureRecognizer:g];
        [g release];
        oCell.pictureThumbButton.userInteractionEnabled = YES;
        
//        [oCell.pictureThumbButton addTarget:self action:@selector(actionPictureThumbButton:) forControlEvents:UIControlEventTouchUpInside];

        if (isUrlExist)
        {
            [oCell.pictureThumbButton setImageWithURL:[NSURL URLWithString:pictureurl] placeholderImage:[UIImage imageNamed:@"loading_default_img.jpg"]];
        }
    }
    else
    {
        if (cell == nil)
        {
            cell = (CommentCell*)[[[CommentCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
        }
        CommentCell *cCell = (CommentCell *)cell;
        NSDictionary *item = [_dataArr objectAtIndex:indexPath.row];
        [cCell.iconButton setImageWithURL:[NSURL URLWithString:[item objectForKey:@"avatar"]] forState:UIControlStateNormal];
        [cCell.commentButton addTarget:self
                                action:@selector(commentButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        cCell.aliasLable.text = [item objectForKey:@"user_name"];
        cCell.timeLbl.text =  [item objectForKey:@"create_time"];
        [cCell.contentLbl setText:[item objectForKey:@"content"]];
        [cCell.replyView reloadReplyData:[item objectForKey:@"re_list"] withHeight:[[item objectForKey:@"replyheight"] floatValue]];
    }
    cell.accessoryType = UITableViewCellAccessoryNone;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

-(void)actionPictureTapGestureRecognizer:(UIGestureRecognizer *)g
{
    UIImageView *imgButton = (UIImageView *)g.view;    
    NSString *picurl = [_info objectForKey:@"src"];
    CGRect rect = [imgButton convertRect:imgButton.bounds toView:nil];
    ZoomImageView *zoom = [[ZoomImageView alloc]initWithFrame:[UIScreen mainScreen].bounds withImage:nil delegate:self withUrl:picurl withOriginRect:rect];
    [self.navigationController.view addSubview:zoom];
    [zoom release];
}

-(IBAction)actionPictureThumbButton:(id)sender
{
    NSString *picurl = [_info objectForKey:@"src"];
    UIButton *imgButton = (UIButton *)sender;
    CGRect rect = [imgButton convertRect:imgButton.bounds toView:nil];
    ZoomImageView *zoom = [[ZoomImageView alloc]initWithFrame:[UIScreen mainScreen].bounds withImage:nil delegate:self withUrl:picurl withOriginRect:rect];
    [self.navigationController.view addSubview:zoom];
    [zoom release];
}

-(void)clickAction:(UIGestureRecognizer *)tap
{
    commentID = @"";
    if ([_commentTableView indexPathsForVisibleRows]>0 )
    {
        [_commentTableView scrollToRowAtIndexPath:[[_commentTableView indexPathsForVisibleRows] objectAtIndex:0] atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
    }
    [_commentToolBar resignFirstResponder];
}

-(void)commentButtonAction:(UIButton *)btn
{
    CommentCell *cell = (CommentCell *)[[btn superview] superview];
    NSIndexPath *indexPath = [_commentTableView indexPathForCell:cell];
    commentID = [[_dataArr objectAtIndex:indexPath.row] objectForKey:@"comment_id"];
    [_commentTableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
    [_commentToolBar becomeFirstResponder];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==0)
    {
        NSString *rowContent = [MSTool trimmingWhiteSpaceCharacter:[_info objectForKey:@"content"]];
        CGRect txtViewFrame = _calculateTextView.frame;
        txtViewFrame.size.width  = 260.0f;
        txtViewFrame.size.height = 0.0f;
        _calculateTextView.frame = txtViewFrame;
        [_calculateTextView setText:rowContent];
        [_calculateTextView sizeToFit];
        HYLog(@"NSStringFromCGSize--->%@",NSStringFromCGSize(_calculateTextView.contentSize));
       return  (58+_calculateTextView.contentSize.height + IMG_SIZE.height);
    }
    NSDictionary *item = [_dataArr objectAtIndex:indexPath.row];
    return [[item objectForKey:@"rowheight"] floatValue];
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section == 0)
    {
        return 30;
    }
    else
    {
        return ([_dataArr count]>0)?0.0:30.0f;
    }
}

-(UILabel *)createLbl
{
    UILabel *topHeaderTipLabel = [[UILabel alloc]initWithFrame:CGRectMake(10.0f,0.0f, 300.0f,23.0f)];
    [topHeaderTipLabel setNumberOfLines:1];
    [topHeaderTipLabel setFont:[UIFont systemFontOfSize:14]];
    [topHeaderTipLabel setTextColor:[UIColor grayColor]];
    [topHeaderTipLabel setBackgroundColor:[UIColor clearColor]];
    return topHeaderTipLabel;
}

-(UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *headerView = [[[UIView alloc]initWithFrame:CGRectZero] autorelease];
    if (section == 0)
    {
        UILabel *topHeaderTipLabel = [self createLbl];
               NSString *likeString = [NSString stringWithFormat:@"%@(%@)",HYLocalizedString(@"喜欢"),[_info objectForKey:@"collect_count"]];
        NSString *commentString = [NSString stringWithFormat:@"%@(%d)",HYLocalizedString(@"评论"),[_dataArr count]];
        [topHeaderTipLabel setText:[NSString stringWithFormat:@"%@  %@",commentString,likeString]];
        [headerView addSubview:topHeaderTipLabel];
        [topHeaderTipLabel release];
    }
    else
    {
        if ([_dataArr count]<1)
        {
            UILabel *topHeaderTipLabel = [self createLbl];
            [topHeaderTipLabel setText:HYLocalizedString(@"赶紧抢沙发吧...")];
            [topHeaderTipLabel setTextAlignment:UITextAlignmentCenter];
            [headerView addSubview:topHeaderTipLabel];
            [topHeaderTipLabel release];
        }
    }
    return headerView;
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger c_row = indexPath.row;
    NSInteger s_count = [_dataArr count];
    if (c_row == s_count-1 && nextpage)
    {
        self.commentTableView.tableFooterView = _loadFooterView;
        [self refresh];
    }
    else
    {
        UIView *footer = [[UIView alloc]initWithFrame:CGRectZero];
        self.commentTableView.tableFooterView = footer;
        [footer release];
    }
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
